package com.liang.blog.security.utils;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

/**
 * @Author：YanWenLiang
 * @Date:2024-03-03-20:31
 */
public class verifyCodeUtil {
    private int width;
    private int height;
    private int codeCount;
    private int lineCount;
    private String code = null;
    private BufferedImage bufferedImage = null;

    private static final char[] CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".toCharArray();

    public verifyCodeUtil(int width, int height, int codeCount, int lineCount) {
        this.width = width;
        this.height = height;
        this.codeCount = codeCount;
        this.lineCount = lineCount;
    }

    public String getCode() {
        if (code == null) {
            StringBuilder builder = new StringBuilder();
            Random random = new Random();
            for (int i = 0; i < codeCount; i++) {
                char c = CHARACTERS[random.nextInt(CHARACTERS.length)];
                builder.append(c);
            }
            code = builder.toString();
        }
        return code;
    }

    public BufferedImage generateCaptchaImage(String code) {
        bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics graphics1 = bufferedImage.getGraphics();
        Graphics2D graphics = (Graphics2D) graphics1;

        // 设置背景色
        graphics.setColor(Color.WHITE);
        graphics.fillRect(0, 0, width, height);

        // 画边框
        graphics.setColor(Color.WHITE);
        graphics.drawRect(0, 0, width - 1, height - 1);

        // 画干扰线
        Random random = new Random();
        for (int i = 0; i < lineCount; i++) {
            int x1 = random.nextInt(width);
            int y1 = random.nextInt(height);
            int x2 = random.nextInt(width);
            int y2 = random.nextInt(height);
            graphics.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)));
            graphics.drawLine(x1, y1, x2, y2);
        }

        // 画验证码
        Font font = new Font("Arial", Font.PLAIN, 30);
        graphics.setFont(font);
        for (int i = 0; i < code.length(); i++) {
            graphics.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)));
            graphics.drawString(String.valueOf(code.charAt(i)), width / codeCount * i + 5, height - 5);
        }

        graphics.dispose();
        return bufferedImage;
    }
}
